/**
 * Created by 居胜 on 2016/5/17.
 */
(function () {

    function $(className){
        return document.getElementsByClassName(className);
    }

    //封装事件绑定
    function bindEvent(ele, event_name, func){
        if(ele.addEventListener){
            event_name = event_name.replace(/^on/,"");
            ele.addEventListener(event_name, func, false);
        }else if(ele.attachEvent){
            ele.attachEvent(event_name, func);
        }else{
            ele[event_name] = func;
        }
    }

    var node = $("container").item(0);
    var order =[];
    var rendingFlag = false;

    //渲染函数
    function render(data){
        var timer = setInterval(changeColor, 500);
        var i = 0;
        rendingFlag = true;

        function changeColor(){
            if( i === 0){
                order[i].style.backgroundColor = "darkseagreen";
                i++;
            }else if( i < order.length){

                //查找关键词
                if(data && order[i-1].innerText === data){
                    order[i-1].style.backgroundColor = "#e74f4d" +
                        ""
                }else{
                    order[i-1].style.backgroundColor = "#fff";
                }
                order[i].style.backgroundColor="darkseagreen";
                i++;
            }else {
                clearInterval(timer);
                rendingFlag = false;
                order[i-1].style.backgroundColor = "#fff";
                reset();
            }
        }
    }

    //前序遍历
    function traverseDF(node){

        (function recurse(currentNode) {

            for(var i = 0; i < currentNode.children.length; i++){
                recurse(currentNode.children[i]);
            }
            order.push(currentNode);

        })(node);
    }

    //遍历结束后，在清除定时器的同时，重置order[]
    function reset(){
        order = [];
    }

    function init(){
        if(rendingFlag){
            alert("正在遍历中。。。")
        }else{
            traverseDF(node);
            render();
        }

    }

    function search(){
        if(rendingFlag){
            alert("正在遍历中。。。")
        }else{
            traverseDF(node);
            var content = keyWord.value.trim();
            if( content !== ""){
                render(content);
            }
        }

    }

    bindEvent(document.getElementById("traversal"), "onclick", init);

    //遍历时，搜索关键字
    var keyWord = document.getElementById("key");
    bindEvent(document.getElementById("search"), "onclick", search);

})();